from django.contrib.auth import authenticate, login,logout as out
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from user.form import UserLRForm


class UserView(View):
    def get(self, request):
        # 只需要渲染表单到模板
        form = UserLRForm()
        return render(request, 'user/register.html', {"form": form})

    def post(self, request):
        # 需要处理数据 所以需要把请求里面的用户信息绑定到表单对象
        print(request.POST)
        # 创建表单对象
        form = UserLRForm(request.POST)
        if form.is_valid():
            print(123)
            # 获取通过校验后的数据
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            user = User(username=username)
            user.set_password(password)
            try:
                user.save()
                print(123)
            except IntegrityError:
                message = "该用户名已经被注册"
            else:
                message = "successful"

        return render(request, 'user/register.html', {"message": message, 'form': form})


class LoginView(View):
    def get(self, request):
        form = UserLRForm()
        return render(request, 'user/login.html', {"form": form})

    def post(self, request):
        form = UserLRForm(request.POST)
        if form.is_valid():
            # 获取通过校验后的数据
            username = form.cleaned_data.get("username")
            password = form.cleaned_data.get("password")
            # authenticate可以帮我们完成用户名和密码的校验
            user = authenticate(username=username, password=password)
            if user:
                # 校验通过 把登录后的用户信息放到请求对象中
                login(request, user)
                # 通过get请求获取到后面参数值 也就是下一步要跳转的页面
                next_url = request.GET.get('next')
                if next_url:
                    return redirect(next_url)
                return redirect('index')
            # try:
            #     # auth系统  登录后用户信息维持，会保存到session和cookie
            #     # user = User.objects.get(username=username)
            #
            #     print(123)
            # except User.DoesNotExist:
            #     message = "该用户不存在"
            # else:
            #     # 如果校验的值为真则密码正确
            #     if user.check_password(password):
            #         # 密码正确 创建session信息 会话维持
            #         request.session['username'] = username
            #         # 自定义过期时间 单位秒
            #         # request.session.set_expiry(30)
            #         return redirect('index')
            #     else:
            #         message = '密码错误'

        return render(request, 'user/login.html', {'form': form})


def logout(request, **kwargs):
    # 刷新会话信息
    # request.session.flush()
    out(request)
    return redirect('login')
